/*客户等级权益页面
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\CustomerManage\RightsAndInterests\List\index.tsx
 * @Date: 2021-12-06 16:49:09
 * @LastEditTime: 2021-12-06 17:10:17
 */
import React from 'react'
import {
  BaseListPage,
  columnRenders,
  http,
  IBaseListPageState,
  IBaseListPageProps,
  UdDrawer,
  uaaApp,
  UdModalForm,
  validators,
  UdModal,
} from '@/lib'

import { Button, Select, Spin } from 'antd'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import apis from '@/apis/CustomerManage'
import comApis from '@/apis'
import AdjustmentRecord from '../component/AdjustmentRecord'
import { downBlobFile } from '@/utils/methods'
import dayjs from 'dayjs'
import ImportExcel from '../component/ImportExcel'
import ImportRecord from '../component/ImportRecord'
import LevelChangeDrawer from '../component/LevelChangeDrawer'
import RightsAndInterestsDetailDrawer from '../component/RightsAndInterestsDetailDrawer'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
dayjs.extend(isSameOrAfter)
const { Option } = Select
const exportBtn = 'user_customer_level_RightsAndInterests_export' //导出
const importBtn = 'user_customer_level_RightsAndInterests_import' //导入
const importRecordBtn = 'user_customer_level_RightsAndInterests_import_record' //导入记录
const adjustmentRecordBtn = 'user_customer_level_RightsAndInterests_adjustment_record' //调整记录
const downloadTemplateBtn = 'user_customer_level_RightsAndInterests_download_template' //下载模板
const tableLevelChangeBtn = 'user_customer_level_RightsAndInterests_level_change' //等级调整
const tableDetailBtn = 'user_customer_level_RightsAndInterests_table_detail' //查看详情
export default class RightsAndInterests extends BaseListPage<IProps, IState> {
  protected useConditionsField = true
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandList = udMainStore.brandList
  constructor(props) {
    super(props)
    this.state = {
      title: '客户等级权益',
      queryApi: apis.getRightsDetailList,
      method: 'POST',
      rowKey: 'id',
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
        },
        { label: '客户编码', id: 'customerCode' },
        { label: '客户名称', id: 'customerName' },
        {
          label: '评级年度',
          id: 'appraiseYear',
          initialValue: dayjs().year() + '',
          render: () => <UdSelect options={this.state.yearList} showSearch allowClear={false} />,
        },
        {
          label: '评级等级',
          id: 'appraiseGrade',
          render: (
            <Select>
              <Option value="VIP">VIP</Option>
              <Option value="A">A级</Option>
              <Option value="B">B级</Option>
              <Option value="C">C级</Option>
            </Select>
          ),
        },
      ],
      columns: [
        // { title: '排名', dataIndex: 'ranking', minWidth: '100px' },
        { title: '客户编码', dataIndex: 'customerCode', minWidth: '100px' },
        { title: '客户名称', dataIndex: 'customerName', minWidth: '150px' },
        { title: '品牌公司', dataIndex: 'brandName', minWidth: '150px' },
        { title: '评级年度', dataIndex: 'appraiseYear', minWidth: '50px' },
        { title: '评级等级', dataIndex: 'appraiseGrade', minWidth: '50px' },
        { title: '享受权益数', dataIndex: 'enjoyRights', minWidth: '50px' },
        {
          title: '评级时间',
          dataIndex: 'createTime',
          minWidth: '140px',
        },
        {
          title: '操作',
          dataIndex: 'operate',
          minWidth: '100px',
          render: columnRenders.operate([
            { title: '等级调整', auth: tableLevelChangeBtn, action: (text, record) => this.openLevelChange(record) },
            { title: '查看', auth: tableDetailBtn, action: (text, record) => this.openDetail(record) },
          ]),
        },
      ],
      leftBtns: [
        uaaApp.canUse(downloadTemplateBtn) && (
          <Button type="primary" onClick={this.handShowDownloadModal}>
            下载模板
          </Button>
        ),
        uaaApp.canUse(importBtn) && (
          <Button type="primary" onClick={this.handShowImportDrawer}>
            导入
          </Button>
        ),
        uaaApp.canUse(exportBtn) && (
          <Button type="primary" onClick={this.handExportTableData}>
            导出
          </Button>
        ),
      ],
      rightBtns: [
        uaaApp.canUse(importRecordBtn) && (
          <Button type="default" onClick={this.openImportRecord}>
            导入记录
          </Button>
        ),
        uaaApp.canUse(adjustmentRecordBtn) && (
          <Button type="default" onClick={this.openAdjustmentRecord}>
            调整记录
          </Button>
        ),
      ],
      uploading: false,
      downloading: false,
      yearList: [],
      tableProps: {
        rowSelection: null,
      },
    }
  }

  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '请求中，请稍后...'}
      >
        {super.render()}
      </Spin>
    )
  }

  componentDidMount() {
    super.componentDidMount()
    this.getYearList()
  }

  private getYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const yearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ yearList }, () => {})
    })
  }

  private handShowDownloadModal = () => {
    let year = dayjs().year()
    let currDate = dayjs()
    let flagDate = dayjs().month(10).date(1).hour(0).minute(0).second(0)
    if (currDate.isSameOrAfter(flagDate)) {
      year++
    }
    UdModal.open({
      title: '下载模板',
      maskClosable: false,
      content: (
        <UdModalForm
          items={[
            {
              label: '品牌公司',
              id: 'brandCode',
              rules: [validators.required],
              render: <UdSelect showSearch options={this.brandList} />,
            },
            {
              id: 'year',
              label: '评级年度',
              rules: [validators.required],
              initialValue: year,
              render: <UdSelect options={this.state.yearList} showSearch disabled />,
            },
          ]}
        />
      ),
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        return this.handDownloadTemplate(values)
      },
    })
  }
  private handShowImportDrawer = () => {
    let { brandCode } = this.queryParams.conditions
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    UdDrawer.open({
      title: `导入客户等级权益-${brandName}`,
      width: '40%',
      content: <ImportExcel brandCode={this.queryParams.conditions.brandCode} />,
      onSubmit: () => {
        this.query()
      },
    })
  }

  private handExportTableData = (): void => {
    this.setState({ downloading: true })
    let { appraiseYear, brandCode } = this.queryParams.conditions
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    http
      .post(apis.exportTableData, this.queryParams, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `${appraiseYear}年-${brandName}-经销商等级权益`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private handDownloadTemplate = (params: any): void => {
    http.get(apis.downTemplate, { params, responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '客户等级权益模板')
      } else {
        return Promise.reject()
      }
    })
  }

  private openAdjustmentRecord = (): void => {
    UdDrawer.open({
      title: '调整记录',
      content: <AdjustmentRecord brandList={this.brandList} yearList={this.state.yearList} />,
      width: '70%',
      footer: false,
    })
  }

  private openImportRecord = (): void => {
    UdDrawer.open({
      title: '导入记录',
      content: <ImportRecord brandList={this.brandList} yearList={this.state.yearList} />,
      width: '70%',
      footer: false,
    })
  }

  private openLevelChange = (record): void => {
    UdDrawer.open({
      title: '等级调整',
      width: '50%',
      content: <LevelChangeDrawer record={record} />,
    })
  }

  private openDetail = (record): void => {
    UdDrawer.open({
      title: '查看详情',
      width: '50%',
      content: <RightsAndInterestsDetailDrawer record={record} />,
      footer: null,
    })
  }
}

interface IState extends IBaseListPageState {
  uploading: boolean
  downloading: boolean
  yearList: any[]
}

interface IProps extends IBaseListPageProps {}
